<?php
class Inquiry Extends MY_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->load->model(array('M_levels','M_users','M_new_enrollee','M_for_enrollment_id','M_pre_applicant','M_fees','M_school_years'));
		$this->load->library(array('authlink','create_captcha','token'));
		$this->_generate_transaction();
	}
	
	public function index()
	{
		$this->_check_transaction();
		$this->load->helper('file');//load helper file
		delete_files('./captcha');// delete all images in captcha folder
		$captcha = $this->create_captcha->_captcha();
		$this->session->set_flashdata('image_url',$captcha->link);
		$this->session->set_userdata('enrollment_finished',FALSE);
		$this->session->set_userdata('enrollment_type',NULL);
		$this->authlink->clear_authlink();
		$this->session->set_userdata('captchaword',$captcha->word);
		$this->view_data['question'] = $captcha->image;
		$this->view_data['system_message'] = $this->_msg();
		$this->view_data['token'] = $this->token->get_token();
	}
	
	public function applicant()
	{
		$this->_check_transaction();
		$this->disable_browser_cache = TRUE;
		$this->form_validation->set_rules('captcha_answer','','trim|htmlspecialchars');
		$this->form_validation->set_rules('broommm','','trim|htmlspecialchars');
			if($this->token->validate_token($this->input->post('broommm'))):
				$captcha_fs = $this->session->userdata('captchaword');
				if(STRTOLOWER($captcha_fs) == STRTOLOWER($this->input->post('captcha_answer'))):
				
					$this->session->set_userdata('inquiry_finished',FALSE);
					$this->session->set_userdata('enrollment_type','Inquiry');
					redirect('inquiry/applicant_data');
				else:
					$captcha = $this->create_captcha->_captcha();
					$this->token->reset();
					$this->session->set_userdata('captchaword',$captcha->word);
					$this->_msg('e','Invalid Captcha Answer','inquiry');
				endif;
			else:
					$this->_msg('e','Invalid Token','inquiry');
			endif;
	}
	
	public function applicant_data()
	{
		$this->_check_transaction();
		$this->disable_browser_cache = TRUE;
		$this->view_data['system_message'] = $this->_msg();
		$this->view_data['class_error'] = NULL;
		$this->view_data['token'] = $this->token->get_token();
		
		if($this->session->userdata('enrollment_type') == 'Inquiry'):
			if($this->session->userdata('inquiry_finished') == FALSE):
				$this->load->helper('misc');
				$set_sy = $this->M_school_years->get_set_school_year();
				$this->view_data['sy'] = $this->M_school_years->get_sy_starting($set_sy->sy_from,$set_sy->sy_to);
				$this->view_data['levels'] = $this->M_levels->get_all_levels_array();
				$this->view_data['feedata'] = $feedata = $this->M_fees->get_assessment_fees_by_grade_level();
				$this->form_validation->set_error_delimiters('<span class="error_simple">', '</span>');
				if($this->input->post('inquire') !== FALSE):
					if($this->token->validate_token($this->input->post('brombrom'))):
						if($this->form_validation->run('for_applicant')):
							
							$d = $this->__format(strtolower($this->input->post('child_bdate')));
							$hear_from = array();
							if($this->input->post('billboard') == 'yes')
							{
								array_push($hear_from,'Billboard');
							}
							
							if($this->input->post('signs_brochures') == 'yes')
							{
								array_push($hear_from,'Signs/Brochures');
							}
							
							if($this->input->post('driving_by') == 'yes')
							{
								array_push($hear_from,'Driving By');
							}
							
							if($this->input->post('friends_relatives') == 'yes')
							{
								array_push($hear_from,'Friends/Relatives');
							}
							
							if($this->input->post('website') == 'yes')
							{
								array_push($hear_from,'Website');
							}
							
							if($this->input->post('bluebook') == 'yes')
							{
								array_push($hear_from,'Bluebook');
							}
							
							if($this->input->post('facebook') == 'yes')
							{
								array_push($hear_from,'Facebook');
							}
							
							if($this->input->post('malls') == 'yes')
							{
								array_push($hear_from,'Malls');
							}
							
							if($this->input->post('others') == 'yes')
							{
								array_push($hear_from,'Others');
							}
							
							if($this->input->post('for_others') == 'yes')
							{
								array_push($hear_from,'Others');
								array_push($hear_from,$this->input->post('for_others'));
							}
							
							$hear = '';
							$ctr = 0;
							foreach($hear_from as $k=>$v)
							{
								$ctr++;
								$hear .= $v;
								if($ctr < count($hear_from))
								{
									if($v!='Others'){
										$hear .= ', ';
									}else{
										$hear .= ': ';
									}
								}
							}

							$profile_data['firstname'] = strtolower($this->input->post('child_fname'));
							$profile_data['lastname'] = strtolower($this->input->post('child_lname'));
							$profile_data['middlename'] = strtolower($this->input->post('child_mname'));
							$profile_data['name_ext'] = strtolower($this->input->post('child_name_ext'));
							$profile_data['dob'] = $d->dob;
							$profile_data['age'] = $d->age;
							$profile_data['contact_no'] = $this->input->post('mobile_phone');
							$profile_data['created'] = NOW;
							$school_year = $this->input->post('school_year');
							$schoolyear = explode('_', $school_year);
							$enroll_data['e_ay_id'] = $schoolyear['0'];
							$enroll_data['e_sy_from'] = $schoolyear['1'];
							$enroll_data['e_sy_to'] = $schoolyear['2'];
							$enroll_data['e_enrollee_type'] = 'new';
							$enroll_data['e_grade_level'] = $this->input->post('level_id');
							$enroll_data['hear_from'] = $hear;
							$enroll_data['e_created_at'] = NOW;
							$enroll_data['schedule_for_testing'] = $this->input->post('child_exam').' @ '.$this->input->post('time_id');
							$enroll_data['a_f_description'] = $feedata->fee_desc;
							$enroll_data['a_f_price'] = $feedata->fee_rate;
							
							$this->db->insert('profiles', $profile_data);
							if($this->db->affected_rows() >= 1)
							{
								$enroll_data['e_profile_id '] = $this->db->insert_id();
								$this->db->insert('enrollments', $enroll_data);
								if($this->db->affected_rows() >= 1)
									{
										$message ='Your data was successfully saved. Please visit the school for payments and further instructions.';
										$auth = $this->authlink->generate_authlink();
										$this->_msg('s',$message,'status/success2/'.$auth);
									}else{
										$auth = $this->authlink->generate_authlink();
										$error_number = time().'-'.uniqid(rand(1000,9999));
										$message ='An Error has occured. System failed to insert applicant: '.$profile_data['firstname'].'. Error Number: ('.$error_number.')';
										$message2 ='An Error has occured. System failed to insert applicant: '.$profile_data['firstname'].' in the enrollment table. Error Number: ('.$error_number.')';
										log_message('error',$message2);
										$this->_msg('e',$message,'inquiry');
									}
							}else{
								$auth = $this->authlink->generate_authlink();
								$error_number = time().'-'.uniqid(rand(1000,9999));
								$message ='An Error has occured. System failed to insert applicant: '.$profile_data['firstname'].'. Error Number: ('.$error_number.')';
								$message2 ='An Error has occured. System failed to insert applicant: '.$profile_data['firstname'].' in the profile table. Error Number: ('.$error_number.')';
								log_message('error',$message2);
								$this->_msg('e',$message,'inquiry');
							}

							//if($this->M_pre_applicant->register_complete_info($profile) == TRUE)
							//{
								//$message ='Your data was successfully saved. Please visit the school for payments and further instructions.';
								//$auth = $this->authlink->generate_authlink();
								//$this->_msg('s',$message,'status/success2/'.$auth);
							//}else{
								//$auth = $this->authlink->generate_authlink();
								//$error_number = time().'-'.uniqid(rand(1000,9999));
								//$message ='An Error has occured. System failed to insert applicant: '.$profile['child_fname'].'. Error Number: ('.$error_number.')';
								//$message2 ='An Error has occured. System failed to insert applicant: '.$profile['child_fname'].' in the pre_applicants table. Error Number: ('.$error_number.')';
								//log_message('error',$message2);
								//$this->_msg('e',$message,'inquiry');
							//}
						endif;
					else:
						$this->token->restart();
						$this->_msg('e','Token expired or compromised.','inquiry');
					endif;
				endif;
			else:
				redirect('inquiry');
			endif;
		else:
			redirect('inquiry');
		endif;
	}
	
	private function _check_transaction()
	{
		if($this->session->userdata('applicanttransaction') == $this->_generate_transaction())
		{
		
		}else{
			$this->session->sess_destroy();
			redirect();
		}
	}
	
	private function _generate_token()
	{
		$key = "aIradhznlpsVeRae7qztven9lBNwUphE";
		$salt = sha1(date('d-d-d-d-d_d_d_d_d-d-d-d',time()).$key);
		$hash = str_pad($salt,5,'-');
		return $hash;
	}
	
	private function _generate_transaction()
	{
		if($this->session->userdata('applicanttransaction') == FALSE)
		{
			$this->session->userdata('applicanttransaction',$this->_generate_token());
		}
	}
	
	public function quitinquiry()
	{
		$this->session->sess_destroy();
		redirect('inquiry');
	}

	private function __format($date)
	{
		$date = DateTime::createFromFormat('m/d/Y', $date);
		$dob = $date->format('Y-m-d');
		$birthday = strtotime($dob);
		$time = time();
		$seconds = $time - $birthday;
		$age = floor($seconds / 31536000);
		return (object)array('dob'=>$dob,'age'=>$age);
	}
}